/* 
Author: Christian Bailer
Contact address: Christian.Bailer@dfki.de 
Department Augmented Vision DFKI 

                          License Agreement
               For Open Source Computer Vision Library
                       (3-clause BSD License)

Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

  * Redistributions of source code must retain the above copyright notice,
    this list of conditions and the following disclaimer.

  * Redistributions in binary form must reproduce the above copyright notice,
    this list of conditions and the following disclaimer in the documentation
    and/or other materials provided with the distribution.

  * Neither the names of the copyright holders nor the names of the contributors
    may be used to endorse or promote products derived from this software
    without specific prior written permission.

This software is provided by the copyright holders and contributors "as is" and
any express or implied warranties, including, but not limited to, the implied
warranties of merchantability and fitness for a particular purpose are disclaimed.
In no event shall copyright holders or contributors be liable for any direct,
indirect, incidental, special, exemplary, or consequential damages
(including, but not limited to, procurement of substitute goods or services;
loss of use, data, or profits; or business interruption) however caused
and on any theory of liability, whether in contract, strict liability,
or tort (including negligence or otherwise) arising in any way out of
the use of this software, even if advised of the possibility of such damage.
*/

#pragma once

#ifndef RECTTOOLS_HPP_
#define RECTTOOLS_HPP_

//#include <cv.h>
// #include <math.h>
// #include <opencv2/core/core.hpp>
// #include <opencv2/imgproc.hpp>
#include "cv_mat.hpp"

namespace RectTools
{

template <typename t>
inline CvVec2<t> center(const CvRect_<t> &rect)
{
    return CvVec2<t> (rect.x + rect.width / (t) 2, rect.y + rect.height / (t) 2);
}

template <typename t>
inline t x2(const CvRect_<t> &rect)
{
    return rect.x + rect.width;
}

template <typename t>
inline t y2(const CvRect_<t> &rect)
{
    return rect.y + rect.height;
}

template <typename t>
inline void resize(CvRect_<t> &rect, float scalex, float scaley = 0)
{
    if (!scaley)scaley = scalex;
    rect.x -= rect.width * (scalex - 1.f) / 2.f;
    rect.width *= scalex;

    rect.y -= rect.height * (scaley - 1.f) / 2.f;
    rect.height *= scaley;
}

template <typename t>
inline void limit(CvRect_<t> &rect, CvRect_<t> limit)
{
    if (rect.x + rect.width > limit.x + limit.width)rect.width = (limit.x + limit.width - rect.x);
    if (rect.y + rect.height > limit.y + limit.height)rect.height = (limit.y + limit.height - rect.y);
    if (rect.x < limit.x)
    {
        rect.width -= (limit.x - rect.x);
        rect.x = limit.x;
    }
    if (rect.y < limit.y)
    {
        rect.height -= (limit.y - rect.y);
        rect.y = limit.y;
    }
    if(rect.width<0)rect.width=0;
    if(rect.height<0)rect.height=0;
}

template <typename t>
inline void limit(CvRect_<t> &rect, t width, t height, t x = 0, t y = 0)
{
    limit(rect, CvRect_<t > (x, y, width, height));
}

inline CvRect getBorder(const CvRect &original, CvRect & limited)
{
    CvRect res;
    res.x = limited.x - original.x;
    res.y = limited.y - original.y;
    res.width = x2(original) - x2(limited);
    res.height = y2(original) - y2(limited);
    assert(res.x >= 0 && res.y >= 0 && res.width >= 0 && res.height >= 0);

    return res;
}

#define CV_BORDER_CONSTANT 0
#define CV_BORDER_REPLICATE 1
inline CvMatU8 subwindow(const CvMatU8 &in, const CvRect & window, int borderType = CV_BORDER_REPLICATE)
{
    TicToc tic;
    CvRect cutWindow = window;
    RectTools::limit(cutWindow, (int32_t)in.cols, (int32_t)in.rows);
    // printf("---------subwindow: [%ld,%ld,%ld,%ld][%ld,%ld,%ld,%ld]\n", window.x, window.y, window.width, window.height,cutWindow.x,cutWindow.y,cutWindow.width,cutWindow.height);
    if (cutWindow.height <= 0 || cutWindow.width <= 0) assert(0); //return CvMat32(window.height,window.width,in.type(),0) ;
    CvRect border = RectTools::getBorder(window, cutWindow);
    // cv::Mat res = in(cutWindow);
    CvMatU8 res;
    if (false) // (border != CvRect(0, 0, 0, 0))
    {
        // cv::copyMakeBorder(res, res, border.y, border.height, border.x, border.width, borderType);
        // printf("----------------------in:[%d,%d]--[%ld, %ld]--!\n", in.rows, in.cols, in.rows+border.y+border.height, in.cols+border.x+border.width);
        TicToc tic1;
        res.resize(in.rows+border.y+border.height, in.cols+border.x+border.width);
        // res.zeros();
        // TODO: borderType
        // CV_BORDER_REPLICATE
        // image
        uint8_t *pSrc, *pDst;
        pSrc = in.data;
        pDst = res.data + border.y*res.cols + border.x;
        long long L2FETCH_PARA = CreateL2pfParam(in.colStride(), in.cols, 1, 0);
        L2fetch( (unsigned int)(pSrc), L2FETCH_PARA);
        for (int r = border.y; r < border.y+in.rows; r++) {
            L2fetch( (unsigned int)(pSrc+in.cols), L2FETCH_PARA);
            memcpy(pDst, pSrc, in.cols);
            pSrc += in.cols;
            pDst += res.cols;
        }
#if 1
        //left
        if (border.x) {
            pSrc = in.data;
            L2FETCH_PARA = CreateL2pfParam(in.colStride(), border.x, 1, 0);
            L2fetch((unsigned int)pSrc, L2FETCH_PARA);
            for (int r = border.y; r < border.y+in.rows; r++) {
                pSrc += in.cols;
                L2fetch((unsigned int)(pSrc), L2FETCH_PARA);
                int x1 = border.x;
                for (int c = 0; c < border.x; c++) {
                    res(r, c) = in(r-border.y, --x1);
                }
            }
        }

        //right
        if (border.width) {
            pSrc = in.data + in.cols - border.width;
            L2FETCH_PARA = CreateL2pfParam(in.colStride(), border.width, 1, 0);
            L2fetch((unsigned int)(pSrc), L2FETCH_PARA);
            for (int r = border.y; r < border.y+in.rows; r++) {
                int x1 = in.cols;
                pSrc += in.cols;
                L2fetch((unsigned int)(pSrc), L2FETCH_PARA);
                for (int c = border.x+in.cols; c < res.cols; c++) {
                    res(r, c) = in(r-border.y, --x1);
                }
            }
        }
        // top
        if (border.y) {
            pSrc = res.data + (2*border.y-1)*res.cols;
            L2FETCH_PARA = CreateL2pfParam(res.colStride(), res.cols, 1, 0);
            L2fetch((unsigned int)(pSrc), L2FETCH_PARA);
            for (int r = 0; r < border.y; r++) {
                pDst = res.data + r*res.cols;
                L2fetch((unsigned int)(pSrc-res.cols), L2FETCH_PARA);
                memcpy(pDst, pSrc, res.cols);
                pSrc -= res.cols; 
            }
        }

        // bottom
        if (border.height) {
            pSrc = res.data + (res.rows-border.height*2-1)*res.cols;
            L2FETCH_PARA = CreateL2pfParam(res.colStride(), res.cols, 1, 0);
            L2fetch((unsigned int)(pSrc), L2FETCH_PARA);
            for (int r = border.y+in.rows; r < res.rows; r++) {
                pDst = res.data + r*res.cols;
                L2fetch((unsigned int)(pSrc-res.cols), L2FETCH_PARA);
                memcpy(pDst, pSrc, res.cols);
                pSrc -= res.cols;
            }
        }
        printf("-----------border-----%lluus----[%ld,%ld,%ld,%ld]----!\n", tic1.toc(), border.x, border.y, border.width, border.height);
#endif
    } else {
        // res = in(cutWindow);
#if 0
        res.resize(cutWindow.height, cutWindow.width);
        for (int i = 0; i < res.rows; i++) {
            for (int j = 0; j < res.cols; j++) {
                res(i, j) = in(i+cutWindow.y, j+cutWindow.x);
            }
        }
#else
        res = in(cutWindow);
#endif
    }
    // printf("-----subwindow:[%ld,%ld,%ld,%ld], %lluus\n", cutWindow.x, cutWindow.y, cutWindow.width, cutWindow.height, tic.toc());
    return res;
}

inline CvMatF32 getGrayImage(CvMatU8 img)
{
    CvMatF32 dst(img.rows, img.cols);
    // if (img.channels() == 3) {
    //     cv::cvtColor(img, img, cv::COLOR_BGR2GRAY);
    // }
    // img.convertTo(img, CV_32F, 1 / 255.f);
    float scale = qhmath_div_f(1, 255.f);
    for (int i = 0; i < img.cols*img.rows; i++) {
        dst.data[i] = img.data[i]*scale;
    }

    return dst;
}

} // end namespace RectTools

#endif // RECTTOOLS_HPP_